package com.xyz.apis.modules.comm.oauth2;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@Component
public class ExpandFilter {

    private final static Logger logger = LoggerFactory.getLogger(ExpandFilter.class);


    /**
     * 拓展过滤器，由OAuth2Filter调用过来
     * return false 没有权限  true 有权限
     * */
    public static Integer doFilter(ServletRequest request, ServletResponse response){
        HttpServletRequest httpRequest = (HttpServletRequest) request;

        //String servletPath = httpRequest.getServletPath();
       // String pathInfo = httpRequest.getPathInfo();
        //String contextPath = httpRequest.getContextPath();
        String requestURI = httpRequest.getRequestURI();
       // StringBuffer requestURL = httpRequest.getRequestURL();
        Map<String, Object> paramValues = getParamValues(httpRequest);

       /* logger.info("------>servletPath:{},pathInfo:{},contextPath:{},requestURI:{},requestURL:{}",
                servletPath,pathInfo,contextPath,requestURI,requestURL);*/

        return getRequestUserInfo(httpRequest,requestURI,paramValues);
    }

    /**
     * 获取请求的token
     */
    private static Integer getRequestUserInfo(HttpServletRequest httpRequest,String requestURI,Map<String, Object> paramValues){
        //从header中获取token
        String token = httpRequest.getHeader("token");

        //如果header中不存在token，则从参数中获取token
        if(StringUtils.isBlank(token)){
            token = httpRequest.getParameter("token");
        }

        return -1;
    }

    /**
     * <p>
     * 从request中获取参数根据键值对形成Map. <br>
     * 注意:对于数组参数，只拷贝了第1个元素.<br>
     * 对于全空格的数据，仍然保留，在保存修改时可能需要.
     * </p>
     *
     * @param request
     * @return map
     * @author liuwei
     */
    protected static Map<String, Object> getParamValues(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
        @SuppressWarnings("rawtypes")
        Enumeration names = request.getParameterNames();
        while (names.hasMoreElements()) {
            String key = (String) names.nextElement();
            String value = request.getParameter(key);
            if (value != null && !"".equals(value)) {
                map.put(key, value);
            }
        }
        return map;
    }
}
